package com.lh.common.sms;

import com.lh.common.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 短信发送工具类
 */
public class SmsSendUtils {

    private static Logger LOGGER = LoggerFactory.getLogger(SmsSendUtils.class);

    public static final String charset = "utf-8";


    /**
     * 通知国际短信
     */
    public static Boolean smsSendInt(String phone, String msg, String account, String secret, String smsSingleRequestServerUrl) {

        String report= "false";

        SmsSendIntRequest smsSingleRequest = new SmsSendIntRequest(account, secret, msg, StringUtils.isNotEmpty(phone)&&phone.length() == 11 ? "0086" + phone : "0091" + phone,report,"");

        String requestJson = JsonUtils.objectToJson(smsSingleRequest);

        LOGGER.info("国际云通讯短信接口请求体: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);

        LOGGER.info("国际云通讯短信接口响应体: " + response);

        SmsSendResponse smsSingleResponse = JsonUtils.jsonToPojo(response, SmsSendResponse.class);
        if(smsSingleResponse.getCode().equals("0")){
            return true;
        }
        return false;
    }
    /**
    　* @description:发送国内短信
    　* @author GaoZien
    */
    public static Boolean smsSend(String phone, String msg, String account, String secret, String smsSingleRequestServerUrl) {

        String report= "true";

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, secret, msg, phone,report);
        String requestJson = JsonUtils.objectToJson(smsSingleRequest);

        LOGGER.info("国内云通讯短信接口请求体: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);

        LOGGER.info("国内云通讯短信接口响应体: " + response);

        SmsSendResponse smsSingleResponse = JsonUtils.jsonToPojo(response, SmsSendResponse.class);
        if(smsSingleResponse.getCode().equals("0")){
            return true;
        }
        return false;
    }

    //eg. param: 0xF0 0x9F 0x8F 0x80
    public static byte[] hexstr2bytes(String hexstr){
        String[] hexstrs = hexstr.split(" ");
        byte[] b = new byte[hexstrs.length];
        for(int i=0;i<hexstrs.length;i++){
            b[i] = hexStringToByte(hexstrs[i].substring(2))[0];
        }
        LOGGER.info("b"+b);
        return b;
    }

    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) ("0123456789ABCDEF".indexOf(achar[pos]) << 4 | "0123456789ABCDEF".indexOf(achar[pos + 1]));
        }
        LOGGER.info("result"+result);
        return result;
    }
}
